import React, { useState } from 'react'
import { Upload, message } from 'antd'
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons'
import { connect } from 'umi'

type Props = {
    dispatch: any
}

function getBase64(img: any, callback: any) {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
}

function beforeUpload(file: any) {
    console.log(file.type)
    const isMp4 = file.type === "video/mp4"
    if (!isMp4) {
        message.error('只能上传mp4格式');
    }
    const isLt100M = file.size / 1024 / 1024 < 100;
    if (!isLt100M) {
        message.error('视频不能超过100MB');
    }
    return isMp4 && isLt100M;
}


function UpLoadVideo({ dispatch }: Props) {
    const [loading, setLoading] = useState(false)
    const [imageUrl, setImageUrl] = useState("")

    function handleChange(info: any) {
        if (info.file.status === 'uploading') {
            setLoading(true)
            return;
        }
        if (info.file.status === 'done') {
            dispatch({ type: "hero/setProps", shipin: true, action: "video", val: info.file.response.url })
            getBase64(info.file.originFileObj, (imageUrl: string) => {
                setLoading(false)
                setImageUrl(imageUrl)
            })
        }
    };
    const uploadButton = (
        <div>
            {loading ? <LoadingOutlined /> : <PlusOutlined />}
            <div style={{ marginTop: 8 }}>Upload</div>
        </div>
    );
    return (
        <Upload
            listType="picture-card"
            className="avatar-uploader"
            showUploadList={false}
            action="/api/upload/introduction"
            beforeUpload={beforeUpload}
            onChange={handleChange}
        >
            {imageUrl ? <video src={imageUrl} style={{ width: '100%' }} /> : uploadButton}
        </Upload>
    )
}

const mapStateToProps = (state: any) => {
    const { hero } = state
    return {
        hero
    }
}

export default connect(mapStateToProps)(UpLoadVideo)